import React, { useEffect, useState } from "react";
import {Tabs,Form,Select,Input,DatePicker,Badge} from 'antd'
import './index.scss'
import LlxForm from 'components/LlxForm/index'
import classNames from 'classnames'
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries,getCount} from 'redux/action'
import LlxTable from 'components/LlxTable'
import { getMessageWord, getMessageLessonAblum,getMessage, getMessageAudio, getMessageVideo, getMessageBook, getMessageBookInten, getMessagePaper, getMessageVideoAblum, getMessageAllStatus, getMessageCountNum } from 'api/index'
import LookMore from 'components/Operations/LookMore'
const {TabPane} = Tabs
const {Search} = Input
const { RangePicker } = DatePicker;

const taskList = [
  {left:26,value:'全部',key:'ALL'},
  {left:85,value:'单词',key:'WORD'},
  {left:145,value:'音频',key:'SONG'},
  {left:204,value:'视频',key:'VIDEO'},
  {left:292,value:'视频专辑',key:'ALBUM_VIDEO'},
  // {left:380,value:'学习视频',key:'LE_VIDEO'},
  {left:455,value:'泛读书',key:'BOOK'},
  {left:514,value:'精读书',key:'IR_BOOK'},
  {left:590,value:'试卷',key:'PAPER'},
  {left:660,value:'主题课',key:'LESSON'}
]


function Task(props) {

const {dictionaries} = props
const [form] = Form.useForm()
const [isModalVisibleMore,setIsModalVisibleMore] = useState(false)
const [loading,setLoading] = useState(false)
const [total,setTotal] = useState(false)
const [tabIndex,setTabIndex] = useState('ALL')
const [selectData,setSelectData] = useState({})
const [countList,setCount] = useState([
  {left:26,key:'All'},
  {left:85,vkey:'WORD'},
  {left:145,key:'SONG'},
  {left:204,key:'VIDEO'},
  {left:292,key:'ALBUM_VIDEO'},
  {left:380,key:'BOOK'},
  {left:455,key:'IR_BOOK'},
  {left:514,key:'PAPER'},
  {left:590,key:'LESSON'}
])
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])

// 表单数据
const formItem = [
  {label: '状态', name: 'status', span: 4 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'dictValue',label:'dictValue'}}
    placeholder={'请选择状态'}
    options={dictionaries.wordStatus}
  >
  </Select>
}},
{label: '创建人', name: 'createBy',  span: 5 ,render: () => {
  return <Select
  allowClear
  optionFilterProp="userName"
  showSearch
  fieldNames={{value:'userName',label:'userName'}}
  placeholder={'请选择创建人'}
  options={dictionaries.UserSpecies}
>
</Select>
}},
{label: '更新人', name: 'updateBy',  span: 5 ,render: () => {
  return <Select
  allowClear
  optionFilterProp="userName"
  showSearch
  fieldNames={{value:'userName',label:'userName'}}
  placeholder={'请选择更新人'}
  options={dictionaries.UserSpecies}
>
</Select>
}},
{label: '更新时间',width:180, name: 'updateTime', span: 5,render: () => {
  return  <RangePicker showTime onChange={getUpdateTime} style={{width:'100%'}}/>
}},
  {label: '', name: 'name' , span: 5,render: () => {
    return  <Search placeholder="请输入关键词搜索" onSearch={getNewList} enterButton />
} }
]
const columns = [
  {title: '名称',fixed:'left', dataIndex: 'name', key: 'name', align: 'center',render: (text, record) => {
    return <div className="operate_link_group text-nowrap text-link" onClick={()=>goInfo(record)}>
      {text}
   </div>
 }},
  {title: '类型', dataIndex: 'type', key: 'type', align: 'center'},
  {title: '状态', dataIndex: 'workStatus', key: 'workStatus', align: 'center'},
  {title: '留言备注', dataIndex: 'remark', key: 'remark', align: 'center'},
  {title: '创建人', dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
    return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
      {text}
   </div>
 }},
  {title: '负责人', dataIndex: 'manager', key: 'manager', align: 'center', render: (text, record) => {
    return <div className={classNames((props.userInfo.user.userName===record.qmanager)||(props.userInfo.user.userName===record.rmanager)?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
    {record.qmanager||record.rmanager}
   </div>
 }},
  {title: '更新人', dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
    return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
    {text}
 </div>
 }},
  {title: '更新时间',width:180, dataIndex: 'updateTime', key: 'updateTime', align: 'center'},
  {title: '操作',fixed:'right', dataIndex: 'operate', key: 'operate', align: 'center',render:(text,row)=>{
    return  <div className="text-link" onClick={()=>getHistory(row)}>
     历史记录
   </div>
  }}
]
// 1.1
useEffect(()=>{
  getNewList()
},[tabIndex]) // eslint-disable-line react-hooks/exhaustive-deps

useEffect(()=>{
  const getTaskCount = async () => {

    const res  = await getMessage()
    props.getCount(res.result)
  }

  getTaskCount()

},[]) // eslint-disable-line react-hooks/exhaustive-deps


// 1.切换tab
const callback = (key)  => {
  setTabIndex(key)
}

// 2.获取数据
const getNewList = async(value) => {

 try {
  setLoading(true)

  const res = await getMessageCountNum()

  const data = [{left:24,key:'ALL',count:props.taskCount},
  {left:87,key:'WORD'},
  {left:147,key:'SONG'},
  {left:206,key:'VIDEO'},
  {left:295,key:'ALBUM_VIDEO'},
  {left:367,key:'BOOK'},
  {left:442,key:'IR_BOOK'},
  {left:502,key:'PAPER'},
  {left:578,key:'LESSON'}]

  data.forEach((i,j)=>{
    if(j===data.length-1) return
     data[j+1].count=res.result[j].count
  })

  setCount(data)

  const params = {
    ...form.getFieldValue(),
    currentStatus:form.getFieldValue().status,
  }
  params.currPage=value&&value.pageSize?value.current:pagination.current
  params.pageSize=value&&value.pageSize?value.pageSize:pagination.pageSize


  delete params.status
  switch(tabIndex){
    case 'ALL':
    const res = await getMessageAllStatus(params)
    setDataSource(res.result.records)
    setTotal(res.result.total)
    break
    case 'WORD':
      const res1 = await getMessageWord(params)
      const data1 = res1.result.records || []
      data1.forEach(i=>{
        i.workStatus=i.wordStatus
        i.name=i.wordName
        i.type='单词'
      })
      setDataSource(data1)
      setTotal(res1.result.total)
    break
    case 'SONG':
      const res2 = await getMessageAudio(params)
      const data2 = res2.result.records || []
      data2.forEach(i=>{
        i.workStatus=i.songStatus
        i.name=i.songName
        i.type='音频'
      })
      setDataSource(data2)
      setTotal(res2.result.total)
    break
    case 'VIDEO':
      const res3 = await getMessageVideo(params)
      const data3 = res3.result.records || []
      data3.forEach(i=>{
        i.workStatus=i.videoStatus
        i.name=i.videoName
        i.type='视频'
      })
      setDataSource(data3)
      setTotal(res3.result.total)
    break
    case 'ALBUM_VIDEO':
      const res4 = await getMessageVideoAblum(params)
      const data4 = res4.result.records || []
      data4.forEach(i=>{
        i.workStatus=i.albumVideoStatus
        i.name=i.albumVideoName
        i.type='专辑'
      })
      setDataSource(data4)
      setTotal(res4.result.total)
    break
    case 'LE_VIDEO':
      const res5 = await getMessageAllStatus(params)
      const data5 = res5.result.records || []
      data5.forEach(i=>{
        i.workStatus=i.videoStatus
        i.name=i.videoName
        i.type='学习视频'
      })
      setDataSource(data5)
      setTotal(res5.result.total)
    break
    case 'BOOK':
      const res6 = await getMessageBook(params)
      const data6 = res6.result.records || []
      data6.forEach(i=>{
        i.workStatus=i.bookStatus
        i.name=i.bookName
        i.type='书籍'
      })
      setDataSource(data6)
      setTotal(res6.result.total)
    break
    case 'PAPER':
      const res7 = await getMessagePaper(params)
      const data7 = res7.result.records || []
      data7.forEach(i=>{
        i.workStatus=i.paperStatus
        i.name=i.paperName
        i.type='试卷'
      })
      setDataSource(data7)
      setTotal(res7.result.total)
    break
    case 'IR_BOOK':
      const res8 = await getMessageBookInten(params)
      const data8 = res8.result.records || []
      data8.forEach(i=>{
        i.workStatus=i.bookStatus
        i.name=i.bookName
        i.type='精读书'
      })
      setDataSource(data8)
      setTotal(res8.result.total)
    break
    case 'LESSON':
      const res9 = await getMessageLessonAblum(params)
      const data9 = res9.result.records || []
      data9.forEach(i=>{
        i.workStatus=i.lessonStatus
        i.name=i.lessonName
        i.type='主题课'
      })
      setDataSource(data9)
      setTotal(res9.result.total)
    break
  default:
    return
  }
 } catch(err){
   console.log(err);
 }
  setLoading(false)
}

// 3.获取时间
const getUpdateTime = (value,dataString) => {
  const data = form.getFieldValue()
  data.startTime=dataString[0]
  data.endTime=dataString[1]
  form.setFieldsValue(data)
}
// 4.去详情
const goInfo =(value)=>{
    switch(value.type) {
      case '主题课':
        props.history.push('/view/plan/themeSubjectInfo?id=' + value.id)
        props.addRouter({
          menuName:'主题课详情',url:'plan/themeSubjectInfo?id=' + value.id 
        })
      break
      case '视频':
        props.history.push('/view/video/videoInfo?id=' + value.id)
        props.addRouter({
          menuName:'视频详情',url:'video/videoInfo?id=' + value.id 
        })
      break
      case '试卷':
        props.history.push('/view/test/testPaperInfo?id=' + value.id)
        props.addRouter({
          menuName:'试卷详情',url:'test/testPaperInfo?id=' + value.id 
        })
      break
      case '单词':
        props.history.push('/view/word/wordInfo?id=' + value.id)
        props.addRouter({
          menuName:'单词详情',url:'word/wordInfo?id=' + value.id 
        })
      break
      case '精读书':
        props.history.push('/view/book/intensiveBookInfo?id=' + value.id)
        props.addRouter({
          menuName:'精读书详情',url:'book/intensiveBookInfo?id=' + value.id 
        })
      break
      case '书籍':
        props.history.push('/view/book/bookInfo?id=' + value.id)
        props.addRouter({
          menuName:'泛读详情',url:'book/bookInfo?id=' + value.id 
        })
      break
      case '专辑':
        props.history.push('/view/video/videoAlbumInfo?id=' + value.id)
        props.addRouter({
          menuName:'专辑详情',url:'video/videoAlbumInfo?id=' + value.id 
        })
      break
      case '音频':
        props.history.push('/view/audio/audioInfo?id=' + value.id)
        props.addRouter({
          menuName:'音频详情',url:'audio/audioInfo?id=' + value.id 
        })
      break
      default:
        return
      }
} 
// 5.历史记录
const getHistory = (value) => {
  setSelectData(value)
  setSelectData({
    id:value.id,
    type:taskList.filter(i=>i.value===value.type)[0].key
  })

  setIsModalVisibleMore(true)
}


  return   <div  className="app-content animate__animated animate__fadeIn overflow">

    <LlxForm form={form} formItem={formItem}/>

   <div className="task-tab">
       <Tabs defaultActiveKey={tabIndex} onChange={callback} >
          {
            taskList.map((i,j)=>{
              return  <TabPane tab={i.value} key={i.key}>
              <LlxTable
                loading={loading} 
                pagination={pagination}
                setPagination={setPagination}
                selectedRowShow={false}
                height={350}
                total={total}
                getNewList={getNewList}
                columns={columns}
                dataSource={dataSource}/>
            </TabPane>
            })
          }
       </Tabs>
         {
         countList.map((i,j)=>{
           return <div key={i.left} style={{position: 'absolute',left: i.left + 'px',top:'4px'}}>
           <Badge count={i.count}></Badge>
           </div>
         })
      }
   </div>

     {/* 查看更多信息 */}
     <LookMore getId={selectData.id} type={selectData.type}    isModalVisible={isModalVisibleMore}  setIsModalVisible={setIsModalVisibleMore} ></LookMore>
       
  </div>
}


// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    getCount: (data) => dispatch(getCount(data)),
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {taskCount:state.taskCount,tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(Task)
